package com.apollographql.apollo.internal;

import com.apollographql.apollo.ApolloCall;
import com.apollographql.apollo.ApolloQueryWatcher;
import com.apollographql.apollo.api.Operation;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.api.internal.ApolloLogger;
import com.apollographql.apollo.api.internal.Optional;
import com.apollographql.apollo.api.internal.Utils;
import com.apollographql.apollo.cache.normalized.ApolloStore;
import com.apollographql.apollo.exception.ApolloCanceledException;
import com.apollographql.apollo.exception.ApolloException;
import com.apollographql.apollo.exception.ApolloHttpException;
import com.apollographql.apollo.exception.ApolloNetworkException;
import com.apollographql.apollo.exception.ApolloParseException;
import com.apollographql.apollo.fetcher.ResponseFetcher;
import com.apollographql.apollo.internal.CallState;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

/* access modifiers changed from: package-private */
public final class RealApolloQueryWatcher<T> implements ApolloQueryWatcher<T> {
    private RealApolloCall<T> activeCall;
    final ApolloStore apolloStore;
    Set<String> dependentKeys = Collections.emptySet();
    final ApolloLogger logger;
    private final AtomicReference<ApolloCall.Callback<T>> originalCallback = new AtomicReference<>();
    final ApolloStore.RecordChangeSubscriber recordChangeSubscriber = new ApolloStore.RecordChangeSubscriber() {
        /* class com.apollographql.apollo.internal.RealApolloQueryWatcher.AnonymousClass1 */

        @Override // com.apollographql.apollo.cache.normalized.ApolloStore.RecordChangeSubscriber
        public void onCacheRecordsChanged(Set<String> changedRecordKeys) {
            if (RealApolloQueryWatcher.this.dependentKeys.isEmpty() || !RealApolloQueryWatcher.areDisjoint(RealApolloQueryWatcher.this.dependentKeys, changedRecordKeys)) {
                RealApolloQueryWatcher.this.refetch();
            }
        }
    };
    private ResponseFetcher refetchResponseFetcher;
    private final AtomicReference<CallState> state = new AtomicReference<>(CallState.IDLE);
    private final ApolloCallTracker tracker;

    RealApolloQueryWatcher(RealApolloCall<T> originalCall, ApolloStore apolloStore2, ApolloLogger logger2, ApolloCallTracker tracker2, ResponseFetcher refetchResponseFetcher2) {
        this.activeCall = originalCall;
        this.apolloStore = apolloStore2;
        this.logger = logger2;
        this.tracker = tracker2;
        this.refetchResponseFetcher = refetchResponseFetcher2;
    }

    @Override // com.apollographql.apollo.ApolloQueryWatcher
    public ApolloQueryWatcher<T> enqueueAndWatch(ApolloCall.Callback<T> callback) {
        try {
            activate(Optional.fromNullable(callback));
            this.activeCall.enqueue(callbackProxy());
            return this;
        } catch (ApolloCanceledException e) {
            if (callback != null) {
                callback.onCanceledError(e);
            } else {
                this.logger.e(e, "Operation: %s was canceled", operation().name().name());
            }
            return this;
        }
    }

    @Override // com.apollographql.apollo.ApolloQueryWatcher
    public synchronized RealApolloQueryWatcher<T> refetchResponseFetcher(ResponseFetcher fetcher) {
        if (this.state.get() == CallState.IDLE) {
            Utils.checkNotNull(fetcher, "responseFetcher == null");
            this.refetchResponseFetcher = fetcher;
        } else {
            throw new IllegalStateException("Already Executed");
        }
        return this;
    }

    /* access modifiers changed from: package-private */
    /* renamed from: com.apollographql.apollo.internal.RealApolloQueryWatcher$3  reason: invalid class name */
    public static /* synthetic */ class AnonymousClass3 {
        static final /* synthetic */ int[] $SwitchMap$com$apollographql$apollo$internal$CallState;

        static {
            int[] iArr = new int[CallState.values().length];
            $SwitchMap$com$apollographql$apollo$internal$CallState = iArr;
            try {
                iArr[CallState.ACTIVE.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.IDLE.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.CANCELED.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.TERMINATED.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    @Override // com.apollographql.apollo.internal.util.Cancelable, com.apollographql.apollo.ApolloQueryWatcher
    public synchronized void cancel() {
        int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i == 1) {
            try {
                this.activeCall.cancel();
                this.apolloStore.unsubscribe(this.recordChangeSubscriber);
            } finally {
                this.tracker.unregisterQueryWatcher(this);
                this.originalCallback.set(null);
                this.state.set(CallState.CANCELED);
            }
        } else if (i == 2) {
            this.state.set(CallState.CANCELED);
        } else if (i != 3) {
            if (i != 4) {
                throw new IllegalStateException("Unknown state");
            }
        }
    }

    @Override // com.apollographql.apollo.internal.util.Cancelable
    public boolean isCanceled() {
        return this.state.get() == CallState.CANCELED;
    }

    @Override // com.apollographql.apollo.ApolloQueryWatcher
    public Operation operation() {
        return this.activeCall.operation();
    }

    @Override // com.apollographql.apollo.ApolloQueryWatcher
    public synchronized void refetch() {
        int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i == 1) {
            this.apolloStore.unsubscribe(this.recordChangeSubscriber);
            this.activeCall.cancel();
            RealApolloCall<T> responseFetcher = this.activeCall.clone().responseFetcher(this.refetchResponseFetcher);
            this.activeCall = responseFetcher;
            responseFetcher.enqueue(callbackProxy());
        } else if (i == 2) {
            throw new IllegalStateException("Cannot refetch a watcher which has not first called enqueueAndWatch.");
        } else if (i == 3) {
            throw new IllegalStateException("Cannot refetch a canceled watcher,");
        } else if (i != 4) {
            throw new IllegalStateException("Unknown state");
        } else {
            throw new IllegalStateException("Cannot refetch a watcher which has experienced an error.");
        }
    }

    @Override // com.apollographql.apollo.ApolloQueryWatcher
    public ApolloQueryWatcher<T> clone() {
        return new RealApolloQueryWatcher(this.activeCall.clone(), this.apolloStore, this.logger, this.tracker, this.refetchResponseFetcher);
    }

    private ApolloCall.Callback<T> callbackProxy() {
        return new ApolloCall.Callback<T>() {
            /* class com.apollographql.apollo.internal.RealApolloQueryWatcher.AnonymousClass2 */

            @Override // com.apollographql.apollo.ApolloCall.Callback
            public void onResponse(Response<T> response) {
                Optional<ApolloCall.Callback<T>> callback = RealApolloQueryWatcher.this.responseCallback();
                if (!callback.isPresent()) {
                    RealApolloQueryWatcher.this.logger.d("onResponse for watched operation: %s. No callback present.", RealApolloQueryWatcher.this.operation().name().name());
                    return;
                }
                RealApolloQueryWatcher.this.dependentKeys = response.getDependentKeys();
                RealApolloQueryWatcher.this.apolloStore.subscribe(RealApolloQueryWatcher.this.recordChangeSubscriber);
                callback.get().onResponse(response);
            }

            @Override // com.apollographql.apollo.ApolloCall.Callback
            public void onFailure(ApolloException e) {
                Optional<ApolloCall.Callback<T>> callback = RealApolloQueryWatcher.this.terminate();
                if (!callback.isPresent()) {
                    RealApolloQueryWatcher.this.logger.d(e, "onFailure for operation: %s. No callback present.", RealApolloQueryWatcher.this.operation().name().name());
                } else if (e instanceof ApolloHttpException) {
                    callback.get().onHttpError((ApolloHttpException) e);
                } else if (e instanceof ApolloParseException) {
                    callback.get().onParseError((ApolloParseException) e);
                } else if (e instanceof ApolloNetworkException) {
                    callback.get().onNetworkError((ApolloNetworkException) e);
                } else {
                    callback.get().onFailure(e);
                }
            }

            @Override // com.apollographql.apollo.ApolloCall.Callback
            public void onStatusEvent(ApolloCall.StatusEvent event) {
                ApolloCall.Callback<T> callback = (ApolloCall.Callback) RealApolloQueryWatcher.this.originalCallback.get();
                if (callback == null) {
                    RealApolloQueryWatcher.this.logger.d("onStatusEvent for operation: %s. No callback present.", RealApolloQueryWatcher.this.operation().name().name());
                    return;
                }
                callback.onStatusEvent(event);
            }
        };
    }

    private synchronized void activate(Optional<ApolloCall.Callback<T>> callback) throws ApolloCanceledException {
        int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i != 1) {
            if (i == 2) {
                this.originalCallback.set(callback.orNull());
                this.tracker.registerQueryWatcher(this);
                this.state.set(CallState.ACTIVE);
            } else if (i == 3) {
                throw new ApolloCanceledException();
            } else if (i != 4) {
                throw new IllegalStateException("Unknown state");
            }
        }
        throw new IllegalStateException("Already Executed");
    }

    /* access modifiers changed from: package-private */
    public synchronized Optional<ApolloCall.Callback<T>> responseCallback() {
        int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i != 1) {
            if (i != 2) {
                if (i != 3) {
                    if (i != 4) {
                        throw new IllegalStateException("Unknown state");
                    }
                }
            }
            throw new IllegalStateException(CallState.IllegalStateMessage.forCurrentState(this.state.get()).expected(CallState.ACTIVE, CallState.CANCELED));
        }
        return Optional.fromNullable(this.originalCallback.get());
    }

    /* access modifiers changed from: package-private */
    public synchronized Optional<ApolloCall.Callback<T>> terminate() {
        int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i != 1) {
            if (i != 2) {
                if (i == 3) {
                    return Optional.fromNullable(this.originalCallback.getAndSet(null));
                } else if (i != 4) {
                    throw new IllegalStateException("Unknown state");
                }
            }
            throw new IllegalStateException(CallState.IllegalStateMessage.forCurrentState(this.state.get()).expected(CallState.ACTIVE, CallState.CANCELED));
        }
        this.tracker.unregisterQueryWatcher(this);
        this.state.set(CallState.TERMINATED);
        return Optional.fromNullable(this.originalCallback.getAndSet(null));
    }

    /* access modifiers changed from: private */
    public static <E> boolean areDisjoint(Set<E> setOne, Set<E> setTwo) {
        if (setOne == null || setTwo == null) {
            return true;
        }
        Set<E> smallerSet = setOne;
        Set<E> largerSet = setTwo;
        if (setOne.size() > setTwo.size()) {
            smallerSet = setTwo;
            largerSet = setOne;
        }
        for (E el : smallerSet) {
            if (largerSet.contains(el)) {
                return false;
            }
        }
        return true;
    }
}
